<template>
  <div>
    <a-tabs defaultActiveKey="1">
      <a-tab-pane key="1" tab="课程结束节序">
        <a-card title="课程结束节序管理" :bordered="false">
          <a-row :gutter="16" style="margin-bottom: 16px">
            <a-col :span="8">
              <a-input-search
                placeholder="输入课程名称或代码搜索"
                v-model="courseSearch"
                @search="handleCourseSearch"
                enterButton
              />
            </a-col>
            <a-col :span="4">
              <a-button type="primary" @click="showAddCourseModal">
                <a-icon type="plus" />添加课程
              </a-button>
            </a-col>
          </a-row>
          
          <a-table
            :columns="courseColumns"
            :dataSource="courseData"
            :pagination="coursePagination"
            :loading="courseLoading"
            rowKey="id"
          >
            <span slot="endSection" slot-scope="text, record">
              <a-input-number
                v-if="record.editing"
                v-model="record.endSection"
                :min="1"
                :max="20"
                style="width: 80px"
              />
              <span v-else>{{ text }}</span>
            </span>
            <span slot="action" slot-scope="text, record">
              <template v-if="record.editing">
                <a @click="saveCourseEdit(record)" style="margin-right: 8px">保存</a>
                <a @click="cancelCourseEdit(record)">取消</a>
              </template>
              <template v-else>
                <a @click="editCourse(record)" style="margin-right: 8px">编辑</a>
                <a-popconfirm
                  title="确定要删除此课程吗?"
                  @confirm="deleteCourse(record.id)"
                  okText="确定"
                  cancelText="取消"
                >
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </span>
          </a-table>
        </a-card>
      </a-tab-pane>
      
      <a-tab-pane key="2" tab="考试课程安排" forceRender>
        <a-card title="考试课程安排申请" :bordered="false">
          <a-row :gutter="16" style="margin-bottom: 16px">
            <a-col :span="6">
              <a-select
                v-model="examSemester"
                placeholder="选择学期"
                style="width: 100%"
              >
                <a-select-option value="2023-1">2023-2024学年第一学期</a-select-option>
                <a-select-option value="2023-2">2023-2024学年第二学期</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-button type="primary" @click="loadExamCourses">查询</a-button>
            </a-col>
          </a-row>
          
          <a-table
            :columns="examCourseColumns"
            :dataSource="examCourseData"
            :pagination="examCoursePagination"
            :loading="examCourseLoading"
            rowKey="id"
          >
            <span slot="examType" slot-scope="text, record">
              <a-select
                v-if="record.editing"
                v-model="record.examType"
                style="width: 120px"
              >
                <a-select-option value="final">期末考试</a-select-option>
                <a-select-option value="class">随堂考试</a-select-option>
                <a-select-option value="batch">分批次考试</a-select-option>
              </a-select>
              <span v-else>
                {{ examTypeMap[text] }}
              </span>
            </span>
            <span slot="status" slot-scope="text">
              <a-badge :status="text === 'approved' ? 'success' : 'processing'" />
              {{ text === 'approved' ? '已安排' : '待审核' }}
            </span>
            <span slot="action" slot-scope="text, record">
              <template v-if="record.editing">
                <a @click="saveExamCourseEdit(record)" style="margin-right: 8px">保存</a>
                <a @click="cancelExamCourseEdit(record)">取消</a>
              </template>
              <template v-else>
                <a @click="editExamCourse(record)" style="margin-right: 8px">编辑</a>
                <a @click="applyExamCourse(record)" style="margin-right: 8px">申请</a>
                <a-popconfirm
                  title="确定要删除此考试安排吗?"
                  @confirm="deleteExamCourse(record.id)"
                  okText="确定"
                  cancelText="取消"
                >
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </span>
          </a-table>
        </a-card>
      </a-tab-pane>
      
      <a-tab-pane key="3" tab="考试任务确定">
        <a-card title="考试任务确定" :bordered="false">
          <a-row :gutter="16" style="margin-bottom: 16px">
            <a-col :span="6">
              <a-select
                v-model="taskSemester"
                placeholder="选择学期"
                style="width: 100%"
              >
                <a-select-option value="2023-1">2023-2024学年第一学期</a-select-option>
                <a-select-option value="2023-2">2023-2024学年第二学期</a-select-option>
              </a-select>
            </a-col>
            <a-col :span="6">
              <a-button type="primary" @click="loadExamTasks">查询</a-button>
            </a-col>
            <a-col :span="6" :offset="6" style="text-align: right">
              <a-button type="primary" @click="showBatchArrangeModal">
                <a-icon type="plus" />批量安排
              </a-button>
            </a-col>
          </a-row>
          
          <a-table
            :columns="examTaskColumns"
            :dataSource="examTaskData"
            :pagination="examTaskPagination"
            :loading="examTaskLoading"
            rowKey="id"
          >
            <span slot="examTime" slot-scope="text, record">
              <a-date-picker
                v-if="record.editing"
                v-model="record.examDate"
                style="width: 120px"
                placeholder="选择日期"
              />
              <a-time-picker
                v-if="record.editing"
                v-model="record.examTime"
                style="width: 120px; margin-left: 8px"
                placeholder="选择时间"
              />
              <span v-else>{{ text }}</span>
            </span>
            <span slot="classroom" slot-scope="text, record">
              <a-select
                v-if="record.editing"
                v-model="record.classroom"
                style="width: 150px"
                showSearch
                optionFilterProp="children"
              >
                <a-select-option v-for="room in classrooms" :key="room.id" :value="room.id">
                  {{ room.name }} (容量: {{ room.capacity }})
                </a-select-option>
              </a-select>
              <span v-else>
                {{ getClassroomName(text) }}
              </span>
            </span>
            <span slot="action" slot-scope="text, record">
              <template v-if="record.editing">
                <a @click="saveExamTaskEdit(record)" style="margin-right: 8px">保存</a>
                <a @click="cancelExamTaskEdit(record)">取消</a>
              </template>
              <template v-else>
                <a @click="editExamTask(record)" style="margin-right: 8px">编辑</a>
                <a-popconfirm
                  title="确定要删除此考试任务吗?"
                  @confirm="deleteExamTask(record.id)"
                  okText="确定"
                  cancelText="取消"
                >
                  <a>删除</a>
                </a-popconfirm>
              </template>
            </span>
          </a-table>
        </a-card>
      </a-tab-pane>
    </a-tabs>
    
    <!-- 添加课程模态框 -->
    <a-modal
      title="添加课程"
      :visible="addCourseModalVisible"
      @ok="handleAddCourseOk"
      @cancel="handleAddCourseCancel"
      :confirmLoading="addCourseLoading"
    >
      <a-form :form="addCourseForm" layout="vertical">
        <a-form-item label="课程代码">
          <a-input
            v-decorator="['code', { rules: [{ required: true, message: '请输入课程代码' }] }]"
          />
        </a-form-item>
        <a-form-item label="课程名称">
          <a-input
            v-decorator="['name', { rules: [{ required: true, message: '请输入课程名称' }] }]"
          />
        </a-form-item>
        <a-form-item label="课程学分">
          <a-input-number
            v-decorator="['credit', { rules: [{ required: true, message: '请输入课程学分' }] }]"
            :min="1"
            :max="10"
            style="width: 100%"
          />
        </a-form-item>
        <a-form-item label="结束节序">
          <a-input-number
            v-decorator="['endSection', { rules: [{ required: true, message: '请输入结束节序' }] }]"
            :min="1"
            :max="20"
            style="width: 100%"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    
    <!-- 批量安排考试模态框 -->
    <a-modal
      title="批量安排考试"
      :visible="batchArrangeModalVisible"
      @ok="handleBatchArrangeOk"
      @cancel="handleBatchArrangeCancel"
      :confirmLoading="batchArrangeLoading"
      width="800px"
    >
      <a-form layout="vertical">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="选择考试日期">
              <a-date-picker
                v-model="batchExamDate"
                style="width: 100%"
                placeholder="选择日期"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="选择考试时间">
              <a-time-picker
                v-model="batchExamTime"
                style="width: 100%"
                placeholder="选择时间"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-form-item label="选择教室">
          <a-select
            v-model="batchClassroom"
            style="width: 100%"
            showSearch
            optionFilterProp="children"
            placeholder="选择教室"
          >
            <a-select-option v-for="room in classrooms" :key="room.id" :value="room.id">
              {{ room.name }} (容量: {{ room.capacity }})
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="选择考试课程">
          <a-transfer
            :dataSource="transferCourses"
            :titles="['可选课程', '已选课程']"
            :targetKeys="targetCourseKeys"
            :render="item => item.title"
            @change="handleTransferChange"
            :listStyle="{
              width: '300px',
              height: '300px',
            }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
export default {
  beforeCreate() {
    this.addCourseForm = this.$form.createForm(this)
  },
  data() {
    return {
      // 课程结束节序相关
      courseSearch: '',
      courseColumns: [
        {
          title: '课程代码',
          dataIndex: 'code',
          key: 'code'
        },
        {
          title: '课程名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '学分',
          dataIndex: 'credit',
          key: 'credit'
        },
        {
          title: '结束节序',
          dataIndex: 'endSection',
          key: 'endSection',
          scopedSlots: { customRender: 'endSection' }
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      courseData: [
        { id: 1, code: 'CS101', name: '计算机科学导论', credit: 3, endSection: 16, editing: false },
        { id: 2, code: 'Mbj007', name: '高等数学（上）	', credit: 4, endSection: 18, editing: false },
        { id: 3, code: 'EN101', name: 'PLC与工业控制技术', credit: 2, endSection: 16, editing: false },
      ],
      coursePagination: {
        current: 1,
        pageSize: 10,
        total: 4
      },
      courseLoading: false,
      addCourseModalVisible: false,
      addCourseLoading: false,
      
      // 考试课程安排相关
      examSemester: '2023-2',
      examCourseColumns: [
        {
          title: '课程代码',
          dataIndex: 'code',
          key: 'code'
        },
        {
          title: '课程名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '考试类型',
          dataIndex: 'examType',
          key: 'examType',
          scopedSlots: { customRender: 'examType' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      examCourseData: [
        { id: 1, code: 'CS101', name: '计算机科学导论', examType: 'final', status: 'approved', editing: false },
        { id: 2, code: 'Mbj007', name: '高等数学（上）	', examType: 'batch', status: 'approved', editing: false },
        { id: 3, code: 'EN101', name: 'PLC与工业控制技术', examType: 'class', status: 'pending', editing: false },
      ],
      examCoursePagination: {
        current: 1,
        pageSize: 10,
        total: 4
      },
      examCourseLoading: false,
      examTypeMap: {
        final: '期末考试',
        class: '随堂考试',
        batch: '分批次考试'
      },
      
      // 考试任务确定相关
      taskSemester: '2023-2',
      examTaskColumns: [
        {
          title: '课程代码',
          dataIndex: 'code',
          key: 'code'
        },
        {
          title: '课程名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '考试类型',
          dataIndex: 'examType',
          key: 'examType',
          render: text => this.examTypeMap[text]
        },
        {
          title: '考试时间',
          dataIndex: 'examTime',
          key: 'examTime',
          scopedSlots: { customRender: 'examTime' }
        },
        {
          title: '教室',
          dataIndex: 'classroom',
          key: 'classroom',
          scopedSlots: { customRender: 'classroom' }
        },
        {
          title: '操作',
          key: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      examTaskData: [
        { 
          id: 1, 
          code: 'CS101', 
          name: '计算机科学导论', 
          examType: 'final', 
          examTime: '2023-06-20 09:00', 
          examDate: null,
          examTimeMoment: null,
          classroom: 1,
          editing: false 
        },
        { 
          id: 2, 
          code: 'Mbj007', 
          name: '高等数学（上）	', 
          examType: 'batch', 
          examTime: '2023-06-21 14:00', 
          examDate: null,
          examTimeMoment: null,
          classroom: 2,
          editing: false 
        }
      ],
      examTaskPagination: {
        current: 1,
        pageSize: 10,
        total: 2
      },
      examTaskLoading: false,
      classrooms: [
        { id: 1, name: '1号教学楼101', capacity: 60 },
        { id: 2, name: '1号教学楼201', capacity: 80 },
        { id: 3, name: '2号教学楼101', capacity: 100 },
        { id: 4, name: '2号教学楼201', capacity: 120 }
      ],
      batchArrangeModalVisible: false,
      batchArrangeLoading: false,
      batchExamDate: null,
      batchExamTime: null,
      batchClassroom: null,
      transferCourses: [
        { key: '3', title: 'PLC与工业控制技术 (EN101)', description: '学分: 2' },
        { key: '4', title: '机电设备故障诊断与维修', description: '学分: 3' }
      ],
      targetCourseKeys: []
    }
  },
  methods: {
    // 课程结束节序相关方法
    handleCourseSearch(value) {
      console.log('搜索课程:', value)
      this.courseLoading = true
      // 模拟搜索
      setTimeout(() => {
        this.courseLoading = false
      }, 500)
    },
    showAddCourseModal() {
      this.addCourseModalVisible = true
    },
    handleAddCourseOk() {
      this.addCourseForm.validateFields((err, values) => {
        if (!err) {
          this.addCourseLoading = true
          // 模拟添加
          setTimeout(() => {
            this.courseData.push({
              id: this.courseData.length + 1,
              code: values.code,
              name: values.name,
              credit: values.credit,
              endSection: values.endSection,
              editing: false
            })
            this.addCourseLoading = false
            this.addCourseModalVisible = false
            this.$message.success('添加课程成功')
            this.addCourseForm.resetFields()
          }, 800)
        }
      })
    },
    handleAddCourseCancel() {
      this.addCourseModalVisible = false
      this.addCourseForm.resetFields()
    },
    editCourse(record) {
      record.editing = true
      this.$set(this.courseData, this.courseData.indexOf(record), record)
    },
    saveCourseEdit(record) {
      record.editing = false
      this.$set(this.courseData, this.courseData.indexOf(record), record)
      this.$message.success('修改成功')
    },
    cancelCourseEdit(record) {
      record.editing = false
      this.$set(this.courseData, this.courseData.indexOf(record), record)
    },
    deleteCourse(id) {
      this.courseData = this.courseData.filter(item => item.id !== id)
      this.$message.success('删除成功')
    },
    
    // 考试课程安排相关方法
    loadExamCourses() {
      this.examCourseLoading = true
      // 模拟加载
      setTimeout(() => {
        this.examCourseLoading = false
      }, 500)
    },
    editExamCourse(record) {
      record.editing = true
      this.$set(this.examCourseData, this.examCourseData.indexOf(record), record)
    },
    saveExamCourseEdit(record) {
      record.editing = false
      this.$set(this.examCourseData, this.examCourseData.indexOf(record), record)
      this.$message.success('修改成功')
    },
    cancelExamCourseEdit(record) {
      record.editing = false
      this.$set(this.examCourseData, this.examCourseData.indexOf(record), record)
    },
    applyExamCourse(record) {
      record.status = 'approved'
      this.$set(this.examCourseData, this.examCourseData.indexOf(record), record)
      this.$message.success('申请成功')
    },
    deleteExamCourse(id) {
      this.examCourseData = this.examCourseData.filter(item => item.id !== id)
      this.$message.success('删除成功')
    },
    
    // 考试任务确定相关方法
    loadExamTasks() {
      this.examTaskLoading = true
      // 模拟加载
      setTimeout(() => {
        this.examTaskLoading = false
      }, 500)
    },
    getClassroomName(id) {
      const room = this.classrooms.find(item => item.id === id)
      return room ? room.name : '未知教室'
    },
    editExamTask(record) {
      // 解析日期和时间
      const [dateStr, timeStr] = record.examTime.split(' ')
      record.examDate = this.$moment(dateStr, 'YYYY-MM-DD')
      record.examTimeMoment = this.$moment(timeStr, 'HH:mm')
      record.editing = true
      this.$set(this.examTaskData, this.examTaskData.indexOf(record), record)
    },
    saveExamTaskEdit(record) {
      // 组合日期和时间
      const dateStr = record.examDate.format('YYYY-MM-DD')
      const timeStr = record.examTimeMoment.format('HH:mm')
      record.examTime = `${dateStr} ${timeStr}`
      record.editing = false
      this.$set(this.examTaskData, this.examTaskData.indexOf(record), record)
      this.$message.success('修改成功')
    },
    cancelExamTaskEdit(record) {
      record.editing = false
      this.$set(this.examTaskData, this.examTaskData.indexOf(record), record)
    },
    deleteExamTask(id) {
      this.examTaskData = this.examTaskData.filter(item => item.id !== id)
      this.$message.success('删除成功')
    },
    showBatchArrangeModal() {
      this.batchArrangeModalVisible = true
    },
    handleBatchArrangeOk() {
      if (!this.batchExamDate || !this.batchExamTime || !this.batchClassroom || this.targetCourseKeys.length === 0) {
        this.$message.error('请填写完整的考试安排信息')
        return
      }
      
      this.batchArrangeLoading = true
      // 模拟批量安排
      setTimeout(() => {
        const dateStr = this.batchExamDate.format('YYYY-MM-DD')
        const timeStr = this.batchExamTime.format('HH:mm')
        
        this.targetCourseKeys.forEach(key => {
          const course = this.examCourseData.find(item => item.id === parseInt(key))
          if (course) {
            this.examTaskData.push({
              id: this.examTaskData.length + 1,
              code: course.code,
              name: course.name,
              examType: course.examType,
              examTime: `${dateStr} ${timeStr}`,
              examDate: null,
              examTimeMoment: null,
              classroom: this.batchClassroom,
              editing: false
            })
          }
        })
        
        this.batchArrangeLoading = false
        this.batchArrangeModalVisible = false
        this.$message.success('批量安排成功')
        this.batchExamDate = null
        this.batchExamTime = null
        this.batchClassroom = null
        this.targetCourseKeys = []
      }, 1000)
    },
    handleBatchArrangeCancel() {
      this.batchArrangeModalVisible = false
      this.batchExamDate = null
      this.batchExamTime = null
      this.batchClassroom = null
      this.targetCourseKeys = []
    },
    handleTransferChange(targetKeys) {
      this.targetCourseKeys = targetKeys
    }
  }
}
</script>
<style lang="less" scoped>
	/deep/ .ant-tabs-bar{
		margin-bottom:0;
	}
	</style>